package com.example.musicdemo;


import static com.example.musicdemo.interfaces.IPlayerControl.PLAYER_START_PAUSE;
import static com.example.musicdemo.interfaces.IPlayerControl.PLAYER_START_PLAY;
import static com.example.musicdemo.interfaces.IPlayerControl.PLAYER_START_STOP;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;

import com.example.musicdemo.databinding.ActivityPlayBinding;
import com.example.musicdemo.interfaces.IPlayerControl;
import com.example.musicdemo.interfaces.IPlayerViewControl;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.util.ArrayList;

public class PlayActivity extends AppCompatActivity {
    private static final String TAG = "PlayActivity";

    private PlayConnection mPlayConnection;
    private IPlayerControl mIPlayerControl;
    private boolean isUserTouchSeekBar = false;
    private IPlayerViewControl mIPlayerViewControl;
    private Song song;


    private Handler handler;
    private int position;
    private ArrayList<Song> musicList;
    private String name;
    private String singerName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityPlayBinding activityPlayBinding = DataBindingUtil.setContentView(this, R.layout.activity_play);
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message message) {
                switch (message.what) {
                    case 1:
                        position = message.arg1;
                        song = musicList.get(position);
                        //拿到音乐的名称
                        name = song.getTitle();
                        //拿到音乐的歌手名字
                        singerName = song.getSinger();
                        activityPlayBinding.textSingerName.setText(singerName);
                        activityPlayBinding.textName.setText(name);
                        mIPlayerControl.playPreMusic(song.getData());

                        break;
                    case 2:
                        position = message.arg1;
                        song = musicList.get(position);
                        name = song.getTitle();//拿到音乐的名称
                        singerName = song.getSinger();//拿到音乐的歌手名字
                        activityPlayBinding.textSingerName.setText(singerName);
                        activityPlayBinding.textName.setText(name);
                        mIPlayerControl.playNextMusic(song.getData());


                        break;


                }


                return false;
            }
        });
        initData(activityPlayBinding);
        initService();
        initEvent(activityPlayBinding);
        initBindService();


    }

    private void initEvent(ActivityPlayBinding activityPlayBinding) {
        activityPlayBinding.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                Log.d(TAG, "onProgressChanged: ");
                //进度条发生改变
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isUserTouchSeekBar = true;
                Log.d(TAG, "onStartTrackingTouch: ");
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int touchSeek = seekBar.getProgress();
                Log.d(TAG, "onStopTrackingTouch: " + touchSeek);
                //当滑动条停止触摸
                if (mIPlayerControl != null) {
                    mIPlayerControl.seekTo(touchSeek);
                }
                isUserTouchSeekBar = false;
            }
        });

        activityPlayBinding.playOrPauseIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "mPlayOrPause-->onClick: ");

                if (mIPlayerControl != null) {

                    mIPlayerControl.playOrPause(song.getData());
                    //播放暂停被点击
                }
            }
        });

        mIPlayerViewControl = new IPlayerViewControl() {
            @Override
            public void seekBarChange(int seek) {
                Log.d(TAG, "seekBarChange: " + Thread.currentThread().getName());
                //从上面可以看出这不是UI线程
                //理论上是不能在非UI线程上更新UI界面的
                //不崩溃的原因:两个控件属于特例：progressBar和surfaceView
                //改变进度条：用户手放上去，就不更新

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!isUserTouchSeekBar) {

                            activityPlayBinding.seekBar.setProgress(seek);
                        }
                    }
                });
            }

            @Override
            public void playerStateChange(int state) {
                switch (state) {
                    case PLAYER_START_PLAY:
                        activityPlayBinding.playOrPauseIv.setBackground(getDrawable(R.mipmap.zanting_o));
                        break;
                    case PLAYER_START_STOP:
                    case PLAYER_START_PAUSE:
                        activityPlayBinding.playOrPauseIv.setBackground(getDrawable(R.mipmap.bofang));
                        break;
                }
            }
        };

        activityPlayBinding.lastSongIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mIPlayerControl.playPreMusic(song.getData());
                if (position != 0) {
                    position--;
                } else {
                    position = musicList.size() - 1;
                }
                Message message = Message.obtain();
                message.what = 1;
                message.arg1 = position;
                handler.sendMessage(message);
            }
        });

        activityPlayBinding.nextSongIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (position != musicList.size() - 1) {

                    position++;
                } else {
                    position = 0;
                }
                Message message = Message.obtain();
                message.what = 2;
                message.arg1 = position;
                handler.sendMessage(message);
            }
        });


    }

    /**
     * 绑定服务
     */
    private void initBindService() {
        Intent intent = new Intent(this, PlayerService.class);
        if (mPlayConnection == null) {
            mPlayConnection = new PlayConnection();
        }
        bindService(intent, mPlayConnection, BIND_AUTO_CREATE);
    }


    private class PlayConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected: ");
            //服务连接
            mIPlayerControl = (IPlayerControl) service;
            mIPlayerControl.registerViewControl(mIPlayerViewControl);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected: ");
            //服务断开
            mIPlayerControl = null;
        }
    }


    /**
     * 初始化服务
     */
    private void initService() {
        startService(new Intent(this, PlayerService.class));
    }

    private void initData(ActivityPlayBinding activityPlayBinding) {
        Intent intent = getIntent();

        musicList = SongUtils.getAllSongs(getBaseContext());
        Bundle bundle = intent.getExtras();
        int position = bundle.getInt("position");

        song = (Song) musicList.get(position);
//        song = intent.getParcelableExtra("song");
//        musicList = intent.getParcelableArrayListExtra("musicList");
//        position = Integer.parseInt(intent.getStringExtra("position"));
//        song = (Song) musicList.get(position);


        String name = this.song.getTitle();//拿到音乐的名称
        String singerName = this.song.getSinger();//拿到音乐的歌手名字
        activityPlayBinding.textSingerName.setText(singerName);
        activityPlayBinding.textName.setText(name);

        Picasso.get().load("https://picsum.photos/300/300")
                .placeholder(activityPlayBinding.imageView4.getBackground())
                .into(activityPlayBinding.imageView4);
        activityPlayBinding.imageView4.setAlpha(0.7f);
        //拿到音乐的存储路径

    }


}